package com.hg.hggood.controller;

import com.hg.hggood.service.ICartService;
import com.hg.hggood.util.JsonResult;
import com.hg.hggood.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@CrossOrigin(value = "http://localhost:8081")
@RequestMapping("carts")
@RestController
public class CartController extends BaseController{
    @Autowired
    private ICartService cartService;

    @RequestMapping("add_to_cart")
    public JsonResult<Void> addToCart(Integer pid,Integer amount,HttpSession session){
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        cartService.addToCart(uid,pid,amount,username);
        return new JsonResult<>(OK);
    }

    @RequestMapping({"","/"})
    public JsonResult<List<CartVO>> getVOByUid(HttpSession session){
        List<CartVO> data = cartService.getVOByUid(getuidFromSession(session));
        return new JsonResult<>(OK,data);
    }

    @RequestMapping({"{cid}/{num}/changenum"})
    public JsonResult<Integer> changeNum(@PathVariable("cid") Integer cid,
                                      @PathVariable("num") Integer num,
                                      HttpSession session){
        Integer data = cartService.ChangeNum(
                cid,
                num,
                getuidFromSession(session),
                getUsernameFromSession(session));
        return new JsonResult<>(OK,data);
    }

    @RequestMapping("list")
    public JsonResult<List<CartVO>> getVOByCid(Integer[] cids,HttpSession session){
        List<CartVO> data = cartService.getVOByCid(getuidFromSession(session),cids);
        return new JsonResult<>(OK,data);
    }

    @RequestMapping("{cid}/delete")
    public JsonResult<Void> delete(@PathVariable Integer cid,
                                   HttpSession session){
        cartService.delete(
                cid,
                getuidFromSession(session),
                getUsernameFromSession(session)
        );
        return new JsonResult<>(OK);
    }
}
